package com.qg.cyapp.activity;

import java.util.List;
import java.util.Map;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;

import com.google.gson.reflect.TypeToken;
import com.qg.cyapp.R;
import com.qg.cyapp.bean.MealTimesBean;
import com.qg.cyapp.util.ShareUtil;

public class ChooseMealTimeActivity extends HttpActivity {

	private RadioGroup rg;
	private Button btSure, btCancel;
	private DatePicker dpDate;
	public static List<MealTimesBean> mealTimes;
	private int choosePosition;

	@Override
	public void afterPost(String result, int requestCode,
			Map<String, String> request) {
		// TODO Auto-generated method stub
		bean = getGsonBean(result);
		if (bean.state == ShareUtil.SUCCESS) {
			mealTimes = gson.fromJson(bean.json,
					new TypeToken<List<MealTimesBean>>() {
					}.getType());
			for (int i = 0; i < mealTimes.size(); i++) {
				RadioButton rb = new RadioButton(this);
				// rb.setVisibility(View.VISIBLE);
				MealTimesBean mtb = mealTimes.get(i);
				rb.setText(mtb.mealTimesName);
				Log.v(TAG, "addView");
				rg.addView(rb, LinearLayout.LayoutParams.FILL_PARENT,
						LinearLayout.LayoutParams.WRAP_CONTENT);
			}
		}
	}

	@Override
	public int getLayoutId() {
		// TODO Auto-generated method stub
		return R.layout.activity_choose_meal_time;
	}

	@Override
	public void setUI() {
		// TODO Auto-generated method stub
		rg = (RadioGroup) findViewById(R.id.rgMealTime);
		btSure = (Button) mfindViewAndSetOnClick(R.id.btSure);
		btCancel = (Button) mfindViewAndSetOnClick(R.id.btCancel);
		dpDate = (DatePicker) findViewById(R.id.dpDate);

		rg.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				// TODO Auto-generated method stub
				Log.v("选中: ", String.valueOf(checkedId));
				choosePosition = checkedId;
			}
		});

		getMealTime();
	}

	private void getMealTime() {
		params.clear();
		params.put("action", "getMealTimes");
		addPostRequest("OrderAction", params, 0);
		sendPostRequest();
	}

	@Override
	public void OnClickListener(View view) {
		// TODO Auto-generated method stub
		switch (view.getId()) {
		case R.id.btSure:
			int day = dpDate.getDayOfMonth();
			int month = dpDate.getMonth() + 1;
			int year = dpDate.getYear();
			String date = String.valueOf(year) + "-" + month + "-" + day;

			Intent intent = new Intent();
			Bundle bundle = new Bundle();
			bundle.putInt(ShareUtil.DATA, choosePosition);
			bundle.putString(ShareUtil.DATE, date);
			intent.putExtras(bundle);
			setResult(RESULT_OK, intent);
			finish();
			break;
		case R.id.btCancel:
			setResult(RESULT_CANCELED);
			finish();
			break;
		}
	}

}
